<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="organizationRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="820"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="box-drawer">
      <div class="drawer-box">
        <div class="box-title">企业基本信息</div>
        <div class="box-form" ref="eleRef" v-loading="infoLoading">
          <BasicForm @register="userForm" />
        </div>
      </div>
      <div class="drawer-box" v-if="drawerInfo.type === operateActionType.VIEW && drawerInfo.authList.length">
        <div class="box-title">产品权限</div>
        <div class="box-form box-list">
          <div class="list-production" v-for="item in drawerInfo.authList" :key="item.appId">
            <div class="production-title">
              {{ item.appName }}
            </div>
            <div class="production-list" v-for="items in item.items" :key="items.authId">
              <div class="list-title">{{ items.authName }}</div>
              <div class="list-time">{{ items.startDate }} 至 {{ items.endDate }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #insertFooter v-if="drawerInfo.type === operateActionType.EDIT">
      <a-button type="primary" @click="resetPwd"> 重置密码 </a-button>
    </template>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import Empty from '@/components/Empty/index.vue'
import { getTenantFormConfig } from '../dataSource'
import { getUpdateSchemaArr } from '@/utils/formSchema'
import { numTransString, getFormatAuthList, scrollToFirstError } from '@/utils'
import { operateActionType } from '@/types/enum'
import { TenantDrawerInfo } from '@/types/tenant'
import { message } from 'ant-design-vue'
import api from '@/api'

const { enterpriseAdd, enterpriseUpdate, enterpriseDetail, getDictItem, platformIndustry, appAuthList } = api

const emit = defineEmits(['operateSuccess', 'register', 'resetPwd'])
const eleRef = ref<null | HTMLElement>(null)

const initRenderData = ref(false)
const infoLoading = ref(false)

const drawerInfo = reactive<TenantDrawerInfo>({
  type: '',
  tenantId: '',
  authList: []
})

const tenantFormConfig = getTenantFormConfig()
const [userForm, { setFieldsValue, getFieldsValue, validate, resetFields, updateSchema, setProps }] =
  useForm(tenantFormConfig)

const [organizationRegister, { closeDrawer, changeOkLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  updateSchema(getUpdateSchemaArr(tenantFormConfig.schemas, data.type))
  if (!initRenderData.value) {
    initRenderData.value = true
    await getDictItemList()
  }
  updateSchema([
    {
      field: 'orgName',
      componentProps: {
        disabled: data.type === operateActionType.EDIT
      }
    },
    {
      field: 'taxesNumber',
      componentProps: {
        disabled: data.type === operateActionType.EDIT
      }
    },
    {
      field: 'contactPhone',
      subLabel: {
        isShow: data.type === operateActionType.ADD
      },
      componentProps: {
        disabled: data.type === operateActionType.EDIT
      }
    },
    {
      field: 'serviceType',
      subLabel: {
        isShow: data.type !== operateActionType.VIEW
      }
    },
    {
      field: 'contactEmail',
      subLabel: {
        isShow: data.type !== operateActionType.VIEW
      }
    },
    {
      field: 'taxPlateType',
      subLabel: {
        isShow: data.type !== operateActionType.VIEW
      }
    },
    {
      field: 'aceId',
      subLabel: {
        isShow: data.type !== operateActionType.VIEW
      }
    },
    {
      field: 'aceKey',
      subLabel: {
        isShow: data.type !== operateActionType.VIEW
      }
    }
  ])

  if (data.type !== operateActionType.ADD) {
    drawerInfo.tenantId = data.tenantId
    try {
      infoLoading.value = true
      let res = await enterpriseDetail({ orgTenantId: data.tenantId })
      infoLoading.value = false
      if (res.result) {
        let result = res.result
        setFieldsValue({
          ...result,
          gaap: numTransString(result.gaap),
          industry: numTransString(result.industry),
          serviceType: numTransString(result.serviceType),
          taxPlateType: numTransString(result.taxPlateType),
          orgStatus: numTransString(result.orgStatus),
          taxesType: numTransString(result.taxesType)
        })
      }
      if (data.type === operateActionType.VIEW) {
        let authRes = await appAuthList({ orgTenantId: data.tenantId })
        let authList = authRes.result || []
        if (authList && authList.length) {
          authList = getFormatAuthList(authList)
        }
        drawerInfo.authList = authList
      }
    } catch (error) {
      infoLoading.value = false
    }
  }
})

// 字典列表
const getDictItemList = async () => {
  try {
    let gaapRes = await getDictItem({ typeCode: 'gaap' })
    let serviceTypeRes = await getDictItem({ typeCode: 'service_type' })
    let taxPlateTypeRes = await getDictItem({ typeCode: 'tax_plate_type' })
    let platformRes = await platformIndustry()
    updateSchema([
      {
        field: 'gaap',
        componentProps: {
          options: gaapRes.result || []
        }
      },
      {
        field: 'serviceType',
        componentProps: {
          options: serviceTypeRes.result || []
        }
      },
      {
        field: 'taxPlateType',
        componentProps: {
          options: taxPlateTypeRes.result || []
        }
      },
      {
        field: 'industry',
        componentProps: {
          options: platformRes.result || []
        }
      }
    ])
  } catch (error) {
    initRenderData.value = false
  }
}
const drawerReset = () => {
  changeOkLoading(false)
  infoLoading.value = false
  drawerInfo.authList = []
  resetFields()
}

const resetPwd = () => {
  emit('resetPwd')
}

// 提交数据
const confirmSubmit = async () => {
  try {
    await validate()
    let formValue = getFieldsValue()
    changeOkLoading(true)
    if (drawerInfo.type === operateActionType.ADD) {
      await enterpriseAdd({
        ...formValue,
        serviceType: formValue.serviceType || '',
        taxPlateType: formValue.taxPlateType || '',
        industry: formValue.industry || ''
      })
    } else if (drawerInfo.type === operateActionType.EDIT) {
      await enterpriseUpdate({
        ...formValue,
        industry: formValue.industry || '', // 可选，清空值为undefined，导致无法更新为空
        serviceType: formValue.serviceType || '',
        taxPlateType: formValue.taxPlateType || '',
        orgTenantId: drawerInfo.tenantId
      })
    }
    message.success(drawerInfo.type === operateActionType.ADD ? '企业新增成功' : '企业编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
    scrollToFirstError(eleRef.value)
  }
}
</script>

<style lang="less" scoped>
.box-drawer {
  padding: 8px 0;
  position: relative;
  .drawer-box {
    margin-bottom: 24px;
    &:last-child {
      margin-bottom: 0;
    }
    .box-title {
      padding-left: 12px;
      padding-bottom: 8px;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
      color: @text-color;
      line-height: 22px;
      position: relative;
      border-bottom: 1px solid #e8e8e8;
      &::before {
        content: '';
        width: 4px;
        height: 16px;
        background: @primary-color;
        border-radius: 2px;
        position: absolute;
        left: 0;
        top: 2px;
      }
    }
    .box-form {
      padding: 24px 24px 4px;
      border: 1px solid #e8e8e8;
      border-radius: 2px;
      position: relative;
      &.box-list {
        padding: 0;
      }
      .list-production {
        color: #192236;
        font-size: 12px;
        font-weight: 600;
        .production-title {
          padding: 10px 0 10px 16px;
          border-top: 1px solid #e8e8e8;
          border-bottom: 1px solid #e8e8e8;
        }
        &:first-child .production-title {
          border-top: none;
        }
        .production-list {
          min-height: 42px;
          padding-left: 16px;
          display: flex;
          align-items: center;
          .list-title {
            min-width: 100px;
          }
        }
      }
    }
  }
  :deep(.ant-form-item-label) {
    font-weight: 600;
    label {
      width: 100%;
    }
  }
}
</style>
